<template>
  <div class="container">
    <div class="margin-container-list">
      <div class="tabs-box">
        <el-tabs type="card" v-model="selectStatus" @tab-click="selectStatusClick">
          <el-tab-pane label="已选优惠券" name="1"></el-tab-pane>
          <el-tab-pane label="未选优惠券" name="0"></el-tab-pane>
        </el-tabs>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default mar-t-20">
        <div class="search-item">
          <el-select class="select-class" v-model="textCol" style="width: 120px">
            <el-option label="券名称" value="couponName"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model="searchKeyword" placeholder="请输入内容" style="width: 200px"></el-input>
          <el-select class="select-class mar-l-20" v-model="couponType" placeholder="选择券类型">
            <el-option label="所有" value=" "></el-option>
            <el-option v-for="(val, key) in dict.couponType" :key="key" :label="val" :value="key"/>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" plain @click="handleSearch">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-button class="batch-btn" v-if="selectStatus == 0" @click="handleBatchSelect">批量添加至已选</el-button>
          <el-button class="batch-btn" v-if="selectStatus == 1" @click="handleBatchRemove">批量移除</el-button>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="couponList" v-loading="listLoading" @selection-change="handleSelectionChange" header-cell-class-name="default-header"      
          row-class-name="default-row" element-loading-text="加载中" style="width: 100%" >
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="200px" label="券名称" prop="couponName">
          </el-table-column>
          <el-table-column min-width="150px" label="类型" prop="couponType">
            <template slot-scope="scope">
              {{dict.couponType[scope.row.couponType]}}
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="适用商品" prop="goodsRange">
            <template slot-scope="scope">
              {{dict.goodsRange[scope.row.goodsRange]}}
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="优惠内容" prop="couponRemark"></el-table-column>
          <el-table-column min-width="150px" label="状态" prop="couponStatus">
            <template slot-scope="scope">
              {{dict.couponStatus[scope.row.couponStatus]}}
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="剩余数量">
            <template slot-scope="scope">
              <span v-if="!scope.row.availableNum && scope.row.availableNum != 0">不限数量</span>
              <span v-else>{{scope.row.availableNum||0}}</span>

            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="赠送数量" v-if="selectStatus == 1">
            <template slot-scope="scope">
              <el-input v-model="scope.row.giveNum" @keyup.native="scope.row.giveNum = checkInputPositiveNum(scope.row.giveNum)" @change="changeGiveNum(scope.row)" maxlength="10" />
            </template>
          </el-table-column>
          <el-table-column min-width="150px" fixed="right" align="right" label="操作">
            <template slot-scope="scope">
              <el-button v-if="selectStatus == 1" type="primary" @click="removeCoupon(scope.row)">移除</el-button>
              <el-button v-if="selectStatus == 0" type="primary" @click="addCoupon(scope.row)">添加至已选</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="searchListQuery.currentPage"
                       :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </div>
    <div class="dialog-footer mar-b-20">
      <el-button type="primary" @click="setCoupon">确定</el-button>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container{
  max-height: 600px;
  overflow-y: auto;
}
.tabs-box{
  /deep/ .el-tabs--card .el-tabs__item{
    height: 40px;
    line-height: 40px;
  }
}
  .user-avatar{
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
  .category-style{
    color: #3abbdb
  }
</style>

<script>
  import { pageSelectCoupon } from '@/api/coupon/coupon'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    components: {},
    directives: {
      // 拖动窗口
      elDragDialog
    },
    props: {
      coupons: {
        type: Array,
        default() {
          return []
        }
      }
    },
    data() {
      return {
        total: null,
        multipleSelection: [],
        listLoading: true,
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          couponNo: '',
          couponName: '',
          couponType: '',
          couponStatus: ''
        },
        textCol: 'couponName',
        searchKeyword: '',
        dict: {
          couponType: {},
          couponStatus: {},
          goodsRange: {}
        },
        couponType: '',
        couponList: [],
        selectStatus: '1',
        pageSelection: {},
        allChecked: false
      }
    },
    // 初始化页面
    created() {
      this.initCouponList()
      this.initDict()
      const that = this
      this.$bus.$on('setCoupon', function(coupons) {
        that.coupons.splice(0, that.coupons.length)
        coupons.forEach(coupon => {
          that.coupons.push(coupon)
        })
        that.initCouponList()
      })
    },
    filters: {
    },
    mounted() {
    },
    methods: {
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initCouponList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initCouponList()
      },
      // 勾选
      handleSelectionChange(items) {
        if (items.length === 0) {
          this.pageSelection[this.searchListQuery.currentPage] = []
        } else {
          this.pageSelection[this.searchListQuery.currentPage] = items
        }
        this.multipleSelection = items
        if (this.multipleSelection.length === this.couponList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.couponList.length) {
          this.couponList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      selectStatusClick() {
        this.resetSearch()
      },
      initDict() {
        getDictByGroupName('CouponDTO').then(response => {
          Object.assign(this.dict, response.data)
        })
      },
      initCouponList() {
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          currentPage: this.searchListQuery.currentPage,
          size: this.searchListQuery.size,
          couponNo: '',
          couponName: '',
          couponStatus: ''
        }
        this.searchListQuery[this.textCol] = this.searchKeyword
        this.searchListQuery.selectStatus = this.selectStatus
        this.searchListQuery.couponType = this.couponType
        this.searchListQuery.couponIds = this.coupons.map(e => e.couponId).join(',')
        this.listLoading = true
        pageSelectCoupon(this.searchListQuery).then(response => {
          this.total = response.data.total || 0
          this.couponList = response.data.records
          this.couponList.forEach(coupon => { this.$set(coupon, 'giveNum', '') })
          Object.assign(this.dict, response.data.dict)
          this.listLoading = false
          if (this.coupons.length > 0 && this.couponList.length > 0) {
            const couponMap = {}
            this.coupons.forEach(coupon => { couponMap[coupon.couponId] = coupon })
            this.couponList.forEach(coupon => {
              // 如果已经填写了赠送数量，回填到页面上
              const editCoupon = couponMap[coupon.couponId]
              if (!editCoupon) {
                return
              }
              coupon.giveNum = editCoupon.giveNum
            })
          }
        })
      },
      handleSearch() {
        this.initCouponList()
      },
      resetSearch() {
        this.textCol = 'couponName'
        this.searchKeyword = ''
        this.searchListQuery.currentPage = 1
        this.searchListQuery.size = 10
        this.initCouponList()
      },
      // 移除券
      removeCoupon(coupon) {
        this.coupons.splice(this.coupons.findIndex(e => e.couponId === coupon.couponId), 1)
        this.initCouponList()
      },
      // 选择券
      addCoupon(coupon) {
        this.coupons.push(coupon)
        this.initCouponList()
      },
      // 批量移除券
      handleBatchRemove() {
        const that = this
        const coupons = this.pageSelection[this.searchListQuery.currentPage]
        coupons.forEach(coupon => that.coupons.splice(that.coupons.findIndex(e => e.couponId === coupon.couponId), 1))
        this.initCouponList()
      },
      // 批量选择券
      handleBatchSelect() {
        const that = this
        const coupons = this.pageSelection[this.searchListQuery.currentPage]
        coupons.forEach(coupon => that.coupons.push(coupon))
        this.initCouponList()
      },
      // 修改赠送数量
      changeGiveNum(coupon) {
        const changeCoupon = this.coupons.find(e => e.couponId === coupon.couponId)
        if (changeCoupon) {
          changeCoupon.giveNum = coupon.giveNum
        }
      },
      // 确定选择券
      setCoupon() {
        for (let i = 0; i < this.coupons.length; i++) {
          if (!this.coupons[i].giveNum) {
            this.$message.error('赠送数量不能为空')
            return
          }
          if (this.coupons[i].couponNum * 1 < this.coupons[i].giveNum * 1) {
            this.$message.error('赠送数量不能大于剩余数量')
            return
          }
        }
        this.$emit('setCoupon', this.coupons)
        this.selectStatus = '1'
        this.resetSearch()
      }
    }
  }

</script>
